<template>
  <div v-if="editOpen">
    <t-table  :selected-row-keys="selectedRowKeys"
              @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
              :columns="columns">

      <template #sort="{ rowIndex }">

        {{ rowIndex + 1 }}
      </template>
      <template #name="{ row }">
        <!--        <t-input clearable @change="() => { if (row.userName !== '') { row.status = 'default' } }" :status="row.status"-->
        <!--          v-model="row.userName">-->
        <!--          <div slot="tips" v-if="row.status === 'error'">不能为空</div>-->
        <!--        </t-input>-->
        <t-select
          v-model="row.name"
          creatable
          filterable
          @change="onLeaderNameChange"
          placeholder="请输入姓名"
          :loading="leaderLoading"
          @search="remoteProjectLeaderMethod"
          :options="nameOptions"
          @create="createProjectLeaderOptions"
          style="width: 200px"
          :status="getStatus(row.name)"
        >
          <div slot="tips" v-if="!row.name">不能为空</div>
        </t-select>
      </template>
      <template #duty="{ row }">
        <t-input clearable style="width:160px" @change="() => { if (row.duty !== '') { row.status = 'default' } }" :status="getStatus(row.duty)"
                 v-model="row.duty">
          <div slot="tips" v-if="!row.duty">不能为空</div>
        </t-input>
      </template>
      <!--        <template #profTitId="{ row }">-->
      <!--          <t-tree-select clearable @change="onProfTitIdChange(row)" filterable style="width:160px"-->
      <!--                         :treeProps="{ keys: { value: 'id' }, valueMode: 'onlyLeaf' }" v-model="row.profTitId"-->
      <!--                         :data="profTitOptions" placeholder="技术职称"  :status="getStatus(row.profTit)">-->
      <!--            <div slot="tips" v-if="!row.profTitId">不能为空</div>-->
      <!--          </t-tree-select>-->
      <!--        </template>-->
      <template #profTit="{ row }">
        <t-select  style="width: 160px" v-model="row.profTit" clearable
                   placeholder="职称等级" :options="dictTypes.prof_tit" :status="getStatus(row.profTit)">
          <div slot="tips" v-if="!row.profTit">不能为空</div>
        </t-select>
      </template>
      <template #company="{row}">
        <t-form-item label="" help="搜索不到请切换是否内部单位后手输" name="company">
          <t-tree-select  v-if="row.isInnerCompany==='1'" style="width:390px" clearable filterable  :status="getStatus(row.company)"
                          :treeProps="{keys: {value: 'label'}}" v-model="row.company" :data="deptMenuOptions"
                          placeholder="选择单位">
            <template #label>
              <t-switch
                size="medium"
                v-model="row.isInnerCompany"
                :label="['内部', '外部']"
                :customValue="['1', '0']"
                @change="()=>{row.company=''}"
              ></t-switch>
            </template>
          </t-tree-select>
          <t-select
            v-else
            v-model="row.company"
            creatable
            filterable
            placeholder="请输入"
            :loading="companyLoading"
            :onSearch="remoteCompanyMethod"
            :options="companyOptions"
            @create="createCompanyOptions"
            style="width: 390px"
          >
            <template #label>
              <t-switch
                size="medium"
                v-model="row.isInnerCompany"
                :label="['内部', '外部']"
                :customValue="['1', '0']"
                @change="()=>{row.company=''}"
              ></t-switch>
              <!--              <t-input  clearable style="width:390px" v-model="row.company"></t-input>-->
            </template>
          </t-select>
          <!--         <t-input v-else clearable style="width:390px" v-model="row.company"></t-input>-->
        </t-form-item>
      </template>
      <template #note="{ row }">
        <t-textarea   tips="不超过200字"
                      placeholder="请输入备注"
                      :maxlength="200" clearable @change="() => { if (row.note !== '') { row.status = 'default' } }"
                      v-model="row.note">
          <!--          <div slot="tips" v-if="!row.note">不能为空</div>-->
        </t-textarea>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table  rowKey="id" :data="data"
              :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
    </t-table>
  </div>
</template>

<script>
import {getDictList} from "@/api/system/dict/data";

export default {
  // dicts:["prof_tit"],
  name: "declaration-description",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    dictTypes:{
      type:Object,
      default:()=>{}
    }
  },
  data() {
    return {
      deptMenuOptions:[],
      companyOptions: [],
      companyLoading: false,
      nameOptions:[],
      leaderLoading:false,
      // dictTypes: {},
      profTitOptions: [],
      selectedRowKeys: [],
      dialogOpen: false,
      header: '新增起草小组成员',
      visible: true,
      formData: {
        sort: null,
        name: '',
        isInnerCompany:'1',
      },
      rules: {
        // name: [
        //   {
        //     required: true,
        //     message: "不能为空",
        //   },
        // ],
        name:[
          {
            required: true,
            message: "名称不能为空",
          },
        ],
        duty:[
          {
            required: true,
            message: "职务不能为空",
          },
        ],
        profTit:[
          {
            required: true,
            message: "职称不能为空",
          },
        ],
        company:[
          {
            required: true,
            message: "所在单位不能为空",
          },
        ],

        // postCode:[
        //   {
        //     required: true,
        //     message: "不能为空",
        //   },
        // ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "名称",
          align: "left",
          ellipsis: true,
          width: 120
        },
        {
          colKey: 'duty',
          title: "职务",
          align: "left",
          ellipsis: true,
          width:120
        },
        {
          colKey: 'profTit',
          title: "职称等级",
          align: "left",
          width:120,
          ellipsis: true
        },
        {
          colKey: 'company',
          title: "所在单位名称",
          align: "left",
          ellipsis: true,
          width:120
        },
        {
          colKey: 'note',
          title: "备注",
          align: "left",
          ellipsis: true,
          width:200
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'name',
          title: "名称",
          align: "left",
          ellipsis: true,
          width: 120
        },
        {
          colKey: 'duty',
          title: "职务",
          align: "left",
          ellipsis: true,
          width:120
        },
        {
          colKey: 'profTit',
          title: "职称等级",
          align: "left",
          width:120,
          ellipsis: true
        },
        {
          colKey: 'company',
          title: "所在单位名称",
          align: "left",
          ellipsis: true,
          width:120
        },
        {
          colKey: 'note',
          title: "备注",
          align: "left",
          ellipsis: true,
          width:200
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val.length > 0 && this.data.length <= 0) {
          this.data = val;
          for (let i=0;i<this.data.length;i++){
            this.data[i].name = this.data[i].name.split("-")[0]
          }
        }
      }
    },
  },
  async mounted() {
    // await this.getDataTypes()
    await this.getProfTitTreeSelect()
    await this.getDeptTreeSelect()
  },
  methods: {
    getDeptTreeSelect(){
      return this.$api.system.dept.treeSelectAllIn().then(response=>{
        this.deptMenuOptions = response.data
      }).catch(e=>{
        this.$message.error(e.toString())
      })
    },
    createCompanyOptions(value){
      this.companyOptions.push({
        label:`${value}`,
        // label:`1`,
        value
      });
    },
    remoteCompanyMethod(search){
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName:search}).then(response => {
        this.companyOptions = response.data.map(val=> ({
          ...val,
          label:`${val.deptName}`,
          value:val.deptName,
        }))
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    getStatus(status){
      return status?"default":"error"
    },
    createProjectLeaderOptions(value){
      this.nameOptions.push({
        label:`${value}`,
        value,
        name: value
      });
    },
    remoteProjectLeaderMethod(search){
      this.leaderLoading = true;
      this.$api.system.member.searchList({name:search}).then(response => {
        this.nameOptions = response.data.map(val=>  ({
          ...val,
          label:`${val.name}-${val.idCard}`,
          value: `${val.name}-${val.idCard}`,
          unitName:val.company,
          name:val.name
        }));
        this.leaderLoading = false;
      }).catch((e) => {
        this.leaderLoading = false;
        this.$message.error(e.toString());
      });
    },
    onLeaderNameChange(val,content) {
      const index = this.nameOptions.findIndex(val=>content?.option?.id === val.id)
      this.nameOptions[index].label= this.nameOptions[index].name;
      // console.log(this.nameOptions[index])
      this.$set(this.nameOptions,index,this.nameOptions[index])
      // Object.assign(this.formData.projectLeader, content.option)
      // console.log(content?.option?.name)
      let index2 = -1
      this.data.forEach((item,index)=>{
        if(item.name.split("-")[0]==val.split("-")[0]){
          index2 = index
        }
      })
      content.option.name = content.option.label
      // const note = this.data[index2].note
      // content.option.note = note
      this.$set(this.data,index2,content.option)
      // this.data[index2].note = note
      // console.log("this.data",this.data)
      // this.$set(this.data,note,"123123")
      // console.log(this.data)
      // this.data.note = "12123123"

      // console.log(content.option)

      // this.$set(this.data,index,content.option)
      // const oldId = this.formData.id;
      // this.formData = content.option || this.nameOptions[index]
      // this.formData.id = oldId;
    },
    getDataTypes() {
      return getDictList(["prof_tit"]).then(response => {
        this.dictTypes = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect() {
      return this.$api.system.profTit.treeselect().then(response => {
        this.profTitOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange(row) {
      if(row.profTitId===undefined){
        this.$set(row,"profTit",undefined)
        return
      }
      this.$api.system.profTit.get(row.profTitId).then(response => {
        this.$set(row,"profTit",response.data.level)
        // this.formData.profTit = response.data.level;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData() {
      // this.$set(this.data[0], 'status', 'error')
      const isValidate = this.data.every((val, index) => {
        Object.keys(val).forEach(item=>{
          if(val[item]===null){
            val[item]=""
          }
        })
        // let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
        // if (!myreg.test(val.phone)) {
        //   this.$message.error(`第${index + 1}条起草小组成员手机号码格式有误`);
        //   return false;
        // }
        if (val.name === ""||val.duty === ""||val.profTit === ""||val.company === "") {
          // this.$set(this.data[index], 'status', 'error')
          this.$message.error(`技术人员：第${index + 1}条内容不能为空`);
          return false;
        }
        // if (val.userName == "") {
        //   this.$set(this.data[index], 'status', 'error')
        //   this.$message.error(`起草单位：第${index + 1}条内容不能为空`);
        //   return false;
        // }
        // this.$set(this.data[index], 'status', 'default')
        return true;
      });
      return isValidate;
    },
    addData() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        name: '',
        isInnerCompany: "1",
        note:"",
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-table td .t-input__tips{
  position: absolute;
}
/deep/ .t-table tr{
  height: 95px;
}
//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}
</style>
